﻿using Colorful.Caching;
using Colorful.Furniture.Extensions;
using Colorful.Furniture.SysManagement;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;

namespace Colorful.Furniture
{
    /// <summary>
    ///  验证码服务
    /// </summary>
    public class VerifyCodeAppService : ApplicationService
    {
        private readonly IRedisCache _cache;

        /// <summary>
        ///  验证码服务
        /// </summary>
        /// <param name="cache"></param>
        public VerifyCodeAppService(IRedisCache cache)
        {
            _cache = cache;
        }


        /// <summary>
        /// 校验验证码有效性
        /// </summary>
        /// <param name="code">要校验的验证码</param>
        /// <param name="id">验证码编号</param>
        /// <param name="removeIfSuccess">验证成功时是否移除</param>
        /// <returns></returns>
        [RemoteService(IsEnabled = false)]
        public bool CheckCode(string code, string id, bool removeIfSuccess = true)
        {
            if (string.IsNullOrEmpty(code))
            {
                return false;
            }

            var key = $"{CachePrefixConst.LoginVerifyCode}:{id}";
            var flag = code.Equals(_cache.Get<string>(key), StringComparison.OrdinalIgnoreCase);
            if (removeIfSuccess && flag)
            {
                _cache.Delete(key);
            }

            return flag;
        }

        /// <summary>
        ///  获取图片验证码的base64路径
        /// </summary>
        public async Task<VerifyCodeOutputDto> GetAsync(string lastVerifyCodeId)
        {
            var id = Guid.NewGuid().ToString("N");
            var key = $"{CachePrefixConst.LoginVerifyCode}:{id}";

            //五分钟有效
            const int seconds = 60 * 5;

            //生成图片
            var imgBase64 = ValidateCoderExtensions.GetBase64String(out string code);

            //如果有之前获取的验证码ID的话则新获取的时候删除
            if (!string.IsNullOrWhiteSpace(lastVerifyCodeId))
                await _cache.DeleteAsync($"{CachePrefixConst.LoginVerifyCode}:{lastVerifyCodeId}");

            //插入缓存
           await _cache.SetAsync(key, code, seconds);

            return new VerifyCodeOutputDto
            {
                Code = $"data:image/png;base64,{imgBase64}",
                Id = id
            };
        }
    }
}